'''
tremchat.py defines a class TremChat. This class sends events taken
from the tremulous server to one php script

Example of use "chat.py":

from sys import argv
import os
from tremapi import TremParserLog
from tremchat import TremChat


if not len(argv)==3:
	print "Use: %s <games.log> <url>" % argv[0]
else:

if os.name=='posix':
	trempath=os.path.join(os.path.expanduser("~"), ".tremulous")
else:
	trempath=os.path.join(os.path.expanduser("~"), "tremulous")


tp=TremParserLogTail(argv[1])
tremchat=TremChat(argv[2])
tp.addListener(tremchat)
tp.run()

Save this script somewhere and execute for example:
python chat.py ~/.tremulous/base/games.log http://yourchat.com/listener.php

Listener.php will be called when an event occurs in the game server
This php script have to catch data from the $_POST['who'] 
and $_POST['msg'] fields

A demo here:
http://www.tremulous-spain.com/tremchat
'''
from urllib import urlopen, urlencode
from tremapi import TremListener

class TremChat(TremListener):
	def __init__(self, url):
		self.player_names={}
		self.url=url
	
	def sendToChat(self, name, msg=None):
		if msg is None:
			msg=name
			name="CONSOLE"
			
		#print ("name: %s\nmessage: %s\n\n" % (name, msg)) #debug
		params=urlencode({'who':name, 'msg':msg});
		u=urlopen(self.url, params);
		
	def say(self, msg):
		self.sendToChat(msg.name, msg.textmsg)
		
	def ClientConnect(self, msg):
		self.player_names[msg.slot]=msg.name
		self.sendToChat(msg.name, "^7conectado...")
	
	def ClientDisconnect(self, msg):
		self.sendToChat(msg.name, "^7desconectado...")
	
	def InitGame(self, msg):
		self.sendToChat("^7comienza una nueva partida");
	
	def Exit(self, msg):
		self.sendToChat(msg.textmsg);
	
	def ShutdownGame(self, msg):
		self.sendToChat("^7Cargando siguiente mapa...")
	ClientTeam=Exit		
	
	def ClientRename(self, msg):
		self.player_names[msg.slot]=msg.name
		self.sendToChat(msg.oldname, "^7ahora se llama %s" % msg.name)
	
